package com.hschinese.pronunciation.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.task.DownloadNewVersionTask;
import com.hschinese.pronunciation.utils.Constant;
import com.hschinese.pronunciation.utils.FileUtils;
import com.hschinese.pronunciation.utils.SharedPreferenceUtils;
import com.hschinese.pronunciation.utils.ThreadPoolUtil;
import com.hschinese.pronunciation.utils.Utils;

import java.util.LinkedList;

public class StartActivity extends BaseActivity {
    private int pics[] = {R.drawable.ic_guide_page};
    private int txts[] = {R.string.guide_1};
    private SparseArray<View> views;
    private LinearLayout mDotsLayout;
    private Long timeAnchor;
    private boolean downloadFinished = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startpage);
        initView();
    }

    private void initView() {
        ViewPager mPage = (ViewPager) findViewById(R.id.pager);
        mDotsLayout = (LinearLayout)findViewById(R.id.guide_dots);
        timeAnchor = System.currentTimeMillis();
        try {
            int version = Utils.getVersionCode(getBaseContext());
            SharedPreferenceUtils sharedPreferenceUtils = SharedPreferenceUtils.getInstance(StartActivity.this);
            int spV = sharedPreferenceUtils.getSharedKeyInt(Constant.VERSION_CODE);
            if(!sharedPreferenceUtils.getSharedKeyB(Constant.FIRST_ENTRY) && version != spV){
//                fileNoMedia();
                initPager();
                initDots();
                mPage.setVisibility(View.VISIBLE);
                mPage.setAdapter(new ImagePagerAdapter(views));
                mPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
                {
                    @Override
                    public void onPageSelected(int arg0) {
                        for (int i = 0; i < mDotsLayout.getChildCount(); i++) {
                            if(i == arg0){
                                mDotsLayout.getChildAt(i).setSelected(true);
                            } else {
                                mDotsLayout.getChildAt(i).setSelected(false);
                            }
                        }
                    }

                    @Override
                    public void onPageScrolled(int arg0, float arg1, int arg2) {

                    }

                    @Override
                    public void onPageScrollStateChanged(int arg0) {

                    }
                });
                sharedPreferenceUtils.setSharedKey(Constant.VERSION_CODE, version);
                sharedPreferenceUtils.setSharedKey(Constant.FIRST_ENTRY,true);
            }else{

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private void fileNoMedia(){
        ThreadPoolUtil.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                FileUtils fileUtils = new FileUtils();
                fileUtils.createNoMediaFile(null);
            }
        });
    }

    private void initPager(){
        views = new SparseArray<>();
        int size = pics.length;
        LayoutInflater inflater = getLayoutInflater();
        for (int i = 0; i < size; i++) {
            View imageLayout = inflater.inflate(R.layout.item_guide_image, null);
            ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
//			imageView.setImageURI(Uri.parse("res://com.hschinese.life/"+pics[i]));
            imageView.setImageResource(pics[i]);
            TextView tv = (TextView) imageLayout.findViewById(R.id.page_start_txt);
            tv.setText(txts[i]);
            TextView mStartBtn = (TextView) imageLayout.findViewById(R.id.page_start_btn);
            if(i != size-1){
                mStartBtn.setVisibility(View.INVISIBLE);
            }else{
                mStartBtn.setVisibility(View.VISIBLE);
                mStartBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        redirect(true);
                    }
                });
            }
            views.append(i, imageLayout);
        }
    }

    private void initDots(){
        int count = pics.length;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(12,12);
        params.setMargins(10, 0, 10, 0);
        for (int j = 0; j < count; j++) {
            ImageButton btn = new ImageButton(this);
            btn.setLayoutParams(params);
            btn.setBackgroundResource(R.drawable.doc_selector);
            mDotsLayout.addView(btn);
        }
        mDotsLayout.getChildAt(0).setSelected(true);
    }


    /**
     * 根据服务器返回结果，询问是否更新
     * 如果是最新版本则提示
     * @param url
     */
    public void askForUpdate(final String url,final boolean isCancel){
        //url不为空说明存在新版本，弹出提示框，询问用户是否下载
        if(!TextUtils.isEmpty(url)){
            Dialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.app_name))
                    .setMessage(getString(R.string.has_new_version))
                    .setPositiveButton(getString(R.string.btn_confirm), new android.content.DialogInterface.OnClickListener() {  //确定更新
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            downLoadNewVersion(url,isCancel);  //下载
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton(isCancel?getString(R.string.setting_exit):getString(R.string.btn_cancel), new android.content.DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if(isCancel){
                                ThreadPoolUtil.getInstance().shutdownNow();
                                LinkedList<Activity> allAtys = MyApplication.getInstance()
                                        .getAllAtys();
                                for (Activity activity : allAtys) {
                                    activity.finish();
                                }
                                android.os.Process.killProcess(android.os.Process.myPid());
                            }else{
                                redirect(false);
                            }
                        }
                    }).create();
            if(isCancel){
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.setCancelable(false);
                alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        return true;
                    }
                });
            }
            alertDialog.show();
        }else {
            redirect(false);
        }
    }

    /**
     * 跳转
     */
    private void redirect(boolean isStart) {
        if(isStart){
            startMainActivity();
            return ;
        }
        Long remainTime = Constant.SPLASH_DISPLAY_LENGTH - (System.currentTimeMillis() - timeAnchor);
        if(remainTime <= 500){
            startMainActivity();
        }else{
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startMainActivity();
                 }
            }, remainTime);
        }
    }

    private void startMainActivity(){
        Intent intent = new Intent(getBaseContext(), MainActivity.class);
        startActivity(intent);
        finish();
    }

    public void downLoadNewVersion(String url,boolean isCancel){
        DownloadNewVersionTask downloadNewVersionTask = new DownloadNewVersionTask(this,isCancel);
        downloadNewVersionTask.execute(url);
    }

    private class ImagePagerAdapter extends PagerAdapter {

        private SparseArray<View> views;

        ImagePagerAdapter(SparseArray<View> views) {
            this.views = views;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(views.get(position));
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            view.addView(views.get(position));
            return views.get(position);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);

        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }
    }
}
